package com.chuanyang.driverh.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.eventbus.ErrorEvent;

import java.io.Serializable;

import de.greenrobot.event.EventBus;



/**
 * Fragment基类
 */
public abstract class BaseFragment extends Fragment implements OnClickListener{
    //加载中
    public static final int LOADING = 1;
    // 加载失败
    public static final int LOADING_FAILED = 2;
    //加载成功
    public static final int LOADING_SUCCESS = 3;
    //加载成功,无数据
    public static final int LOADING_SUCCESS_NULL = 4;
    public View rootView;
    /**
     * 加载中布局，加载失败布局，加载成功显示数据布局
     */
    private View mLoadingLayout, mLoadingFailedLayout, mBaseContent,mSuccessNull;
    /**
     * 加载失败布局中的显示图片和文字
     */
    private TextView mLoadingFailedWifi,mSuccessNullText;
    /**
     * 加载失败后的刷新数据
     */
    private Button mLoadingFailedRefresh;
    protected boolean isPrepared = false;
    public Activity activityContext;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activityContext=getActivity();
        View mView = inflater.inflate(R.layout.base_loading_content, container,false);
        LinearLayout llContent = (LinearLayout) mView.findViewById(R.id.base_loading_content);
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutResId(), null);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        llContent.addView(rootView, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLoadingLayout = view.findViewById(R.id.base_loading_layout);
        mLoadingFailedLayout = view.findViewById(R.id.base_loading_failed_layout);
        mBaseContent = view.findViewById(R.id.base_loading_content);
        mLoadingFailedWifi = (TextView) view.findViewById(R.id.base_loading_failed_wifi);
        mLoadingFailedRefresh = (Button) view.findViewById(R.id.base_loading_failed_refresh);
        mSuccessNull = view.findViewById(R.id.base_message_null);
        mSuccessNullText = (TextView) view.findViewById(R.id.base_message_text);
        mLoadingFailedRefresh.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onForceRefresh();
            }
        });

        initView(view);
        initData();
        initListener();
        isPrepared = true;
    }
    /**
     * 布局资源文件
     *
     * @return
     */
    protected abstract int getLayoutResId();
    protected abstract void initView(View view);
    protected abstract void initData();
    protected abstract void initListener();

    public void visibleToUser() {
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);//此方法的执行比onCreated方法执行的还要早
        if (getUserVisibleHint() && isPrepared) {//页面后台转前台
            visibleToUser();
        }
    }
    /**
     * 点击刷新按钮时刷新数据
     */
    protected  void onForceRefresh(){};


    protected void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    public void startActivity(Class<?> cls, Object obj) {
        Intent intent = new Intent(getActivity(), cls);
        if (obj != null) {
            intent.putExtra("data", (Serializable) obj);
        }
        startActivity(intent);

    }
    public void startActivity(Class<?> cls, String  str) {
        Intent intent = new Intent(getActivity(), cls);
        if (!TextUtils.isEmpty(str)) {
            intent.putExtra("data", str);
        }
        startActivity(intent);

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        registerEventBus();
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        unRegisterEventBus();
        super.onDestroy();
    }
    public void onEventMainThread(ErrorEvent event) {
        int status = event.getStatus();
        String message = event.getMsg();
        if (event.getContext().equals(getActivity())) {
            LogUtils.i("fragment_error_status:" + event.getStatus());
            LogUtils.i("fragment_error_msg:" + event.getMsg());
            onErrorMsg(status, message);
        }
    }
    protected void onErrorMsg(int status, String message) {
        if (status ==  ConstUtil.HTTP_IO_ERROR || status == ConstUtil.HTTP_NET_ERROR
                || status == ConstUtil.HTTP_PARSER_ERROR) {
            onShowFailed();
        }
    }


    protected void registerEventBus() {
        EventBus.getDefault().register(this);
    }

    protected void unRegisterEventBus() {
        EventBus.getDefault().unregister(this);
    }




    /**
     * 显示加载失败布局，当没有连接到服务器或者数据返回有误，此方法会自动调用子类不需要手动调用
     */
    public void onShowFailed() {
        showView(LOADING_FAILED);
    }

    /**
     * 显示加载成功布局
     */
    public void onShowContent() {
        showView(LOADING_SUCCESS);
    }

    /**
     * 显示加载中布局，子类通过showDialogLoading调用此方法
     */
    public void onShowLoading() {
        showView(LOADING);
    }
    /**
     * 显示没有数据时背景，
     */
    public void onShowNull() {
        showView(LOADING_SUCCESS_NULL);
    }

    public void setTextNull(String text){
        mSuccessNullText.setText(text);
    }

    /**
     * 判断显示的View
     *
     * @param index
     */
    private void showView(int index) {
        mLoadingLayout.setVisibility(index == LOADING ? View.VISIBLE: View.GONE);
        mLoadingFailedLayout.setVisibility(index == LOADING_FAILED ? View.VISIBLE: View.GONE);
        mBaseContent.setVisibility(index == LOADING_SUCCESS ? View.VISIBLE: View.GONE);
        mSuccessNull.setVisibility(index == LOADING_SUCCESS_NULL ? View.VISIBLE : View.GONE);
    }

}
